package com.scs.application.modules.fsd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.fsd.entity.FsdGroupRole;
import com.scs.application.modules.fsd.mapper.GroupRoleMapper;
import com.scs.application.modules.fsd.service.GroupRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 */
@Service
public class GroupRoleServiceImpl extends BaseServiceImpl<GroupRoleMapper, FsdGroupRole> implements GroupRoleService {
    @Override
    public List<FsdGroupRole> getGroupsByRole(String id) {
        return baseMapper.getGroupsByRole(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean changeGroupsByRole(String groupIds, String roleId) {
        remove(new QueryWrapper<FsdGroupRole>().eq("role_id", roleId));
        Collection<FsdGroupRole> groupRoles = new ArrayList<>();
        String[] groupIdArray = groupIds.split(",");
        for (String group_id : groupIdArray) {
            if (StringUtils.isBlank(group_id)) continue;
            FsdGroupRole groupRole = new FsdGroupRole();
            groupRole.setGroupId(group_id);
            groupRole.setRoleId(roleId);
            groupRoles.add(groupRole);
        }
        saveBatch(groupRoles);
        return true;
    }

    @Override
    public List<FsdGroupRole> getRolesByGroup(String id) {
        return baseMapper.getRolesByGroup(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean changeRolesByGroup(String roleIds, String groupId) {
        remove(new QueryWrapper<FsdGroupRole>().eq("group_id", groupId));
        Collection<FsdGroupRole> groupRoles = new ArrayList<>();
        String[] roleIdArray = roleIds.split(",");
        for (String role_id : roleIdArray) {
            if (StringUtils.isBlank(role_id)) continue;
            FsdGroupRole groupRole = new FsdGroupRole();
            groupRole.setGroupId(groupId);
            groupRole.setRoleId(role_id);
            groupRoles.add(groupRole);
        }
        saveBatch(groupRoles);
        return true;
    }
}
